function averagePerplexity = cvProcedure(dataVector, y)
%Perform 4-fold cross-validation
cvFolds = 4;

%Split the data into four sets
sizeOfSet = size(dataVector,1)/cvFolds;

%Initialise the values
previousNumRows = 0;

%Declare the average perplexity
averagePerplexity = 0;
%Perform 4-fold cross validation
for jj = 1:cvFolds

%Create the data vector
numRows = sizeOfSet*jj;
%The training data
xtest = dataVector(previousNumRows + 1:numRows,:);
ytest = y(previousNumRows + 1:numRows,:);
%The test data
xtrain = dataVector;
xtrain(previousNumRows + 1:numRows,:) = [];
ytrain = y;
ytrain(previousNumRows + 1:numRows,:) = [];

phi = [ones(size(xtrain,1),1),xtrain];
%phi = [xtrain];
%Learn the parameters for linear regression
inversephi = phi'*phi;

wEstimate = inversephi\(phi'*ytrain);

%Test on the test data
xtestcv = [ones(size(xtest,1),1) xtest];
Nt = size(xtestcv,1);
%xtestcv = [xtest];
%The standard deviation of the data is needed
InverseVariance = (1/size(phi,1))*sum((ytrain - phi*wEstimate).^2);
variance = InverseVariance;

%P(yn|xn)=(1/sqrt(2pi?^2))*exp( (yn-wxn-b)^2/(2*?^2))

%Calculate P(yn|xn)
% for ii = 1:size(ytest,1)
%     if ii==932
%        ii; 
%     end

%LogPyx = (-0.5*log(2*pi*variance)-((ytest - xtestcv*wEstimate).^2)./(2*variance));

LogPyx = log(normpdf(ytest, xtestcv*wEstimate,sqrt(variance)));


% pyx(ii,:) = (1/sqrt(2*pi*variance))*exp(-((ytest(ii,:) - xtestcv(ii,:)*wEstimate)^2)/(2*variance));
% end
%Calculate the perplexity using the test data
% perplexity = calcPerplexity(size(xtest,1), pyx);
%Calculate log P(Yn = y | Xn) 

test = LogPyx;
[maxTest, index] = min(LogPyx)

%logPyx = log(pyx);
sumPyx = sum(LogPyx);
perplexity = exp( -1/Nt .* sumPyx);


%Store the perplexity
averagePerplexity = (averagePerplexity + perplexity);

previousNumRows = numRows;

end

%Calculate the average perplexity
averagePerplexity = averagePerplexity/4;